#!/bin/bash
#
# Wraps a script in a pkg installer.
# When packages are installed, a receipt is recorded in OS X's receipt
# database. That receipt tells OS X whether or not the package has been
# installed. So basically, when you need to run a script on a machine, but you
# only need to run it once, pass it as an argument to this script and you'll
# get a packaged version.
#
# Arguments required are:
#	- the path to the target script
#	- the version to use for the package
#	- an array of catalogs to use when importing the package into munki
#	- the sub directory where the package should be stored in the munki repo
#
# EXAMPLE:
# ======================
# ./createEmptyPkgWithScript.sh awesome.sh "1.0" "dev,testing" "awesome/stuff/"
# 
#

# Grab the script from the args array if one is present.
#
script="${1}"
version="${2}"
catalogs="${3}"
subdir="${4}"

APP=`basename "${0}"`
BASE_DIR=`dirname "${0}"`


if [ "${#}" -lt 4 ]; then
	echo "Usage: ${APP} <script> <version> <catalogs> <subdir>"
	echo "Example: ${APP} awesome.sh 1.0 \"dev,testing\" \"apps/settings\""
	exit
fi

while [ ! -e "${script}" ]
do
	echo -n "[${APP}] Enter a valid path to the script to package: "
	read script
done


if [ -z $version ]; then
	version="1.0"
fi


name=`basename "${script}" | sed 's/\..*$//g'`
pkgName="${PWD}/${name}.pkg"


if [ ! -e "${PWD}/___scripts___" ]; then
	mkdir -p "${PWD}/___scripts___"
fi

cp "${script}" "${PWD}/___scripts___/postinstall"
chmod a+x "${PWD}/___scripts___/postinstall"



emptyDir="${PWD}/very_much_empty___always"
mkdir "${emptyDir}"
pkgbuild \
	--nopayload \
	--root "${emptyDir}" \
	--identifier "edu.denison.${name}" \
	--version "${version}" \
	--scripts "${PWD}/___scripts___" \
	"${pkgName}"
rm -rf "${emptyDir}"


if [ ! -z "${subdir}" ]; then
	subdir="--subdirectory=${subdir}"
fi

if [ ! -z "${catalogs}" ]; then
	catalogs="--catalog=${catalogs}"
fi

echo "[${APP}] wrote package to ${pkgName}"
echo "[${APP}] Importing ${name}.pkg"
/usr/local/munki/munkiimport \
	"${pkgName}"\
	"${catalogs}"\
	--min-os-ver="10.6"\
	"${subdir}"

rm "${pkgName}"
rm -rf "${BASE_DIR}/___scripts___"
